package demos.modifysql;

import gudusoft.gsqlparser.EDbVendor;
import gudusoft.gsqlparser.TGSqlParser;
import gudusoft.gsqlparser.TStatementList;
import gudusoft.gsqlparser.nodes.TExpression;
import gudusoft.gsqlparser.nodes.TResultColumn;
import gudusoft.gsqlparser.nodes.TResultColumnList;
import gudusoft.gsqlparser.stmt.TSelectSqlStatement;

import java.util.LinkedList;
import java.util.stream.StreamSupport;

/**
 * @author chen
 * @date 2023/8/1 16:35
 */
public class replaceTablenameFive {
    public static void main(String[] args) {
        TGSqlParser sqlparser = new TGSqlParser(EDbVendor.dbvmysql);
        sqlparser.sqltext = "SELECT temp.name, max(temp.price) as price \nFROM (\n  SELECT `user`.name,\n         `order`.price\n  FROM   `user`,\n         `order`\n  WHERE  user.id = order.uid \n ) as temp\nGROUP BY temp.name";
        int ret = sqlparser.parse();
        if (ret == 0) {
            TStatementList stmts = sqlparser.getSqlstatements();
            TSelectSqlStatement stmt = (TSelectSqlStatement) stmts.get(0);
            LinkedList<String>[] lineages = new LinkedList[stmt.getResultColumnList().size()];
            TResultColumnList columns = stmt.getResultColumnList();

            for (int i = 0; i < columns.size(); i++) {
                TResultColumn column = columns.getResultColumn(i);
                LinkedList<String> lineage = lineages[i] = new LinkedList<>();
                lineage.addFirst(String.format("%s(RS-1)", column.getDisplayName()));
                String ColumnName = column.getDisplayName();
                String prefix = "";

                // 获取 alias
                TExpression expr = column.getExpr();
                if (column.getExpr().getFunctionCall() != null) {
                    // 获取函数参数
                    while (expr.getFunctionCall() != null) {
                        expr = expr.getFunctionCall().getArgs().getExpression(0);
                    }
                    prefix = expr.toString().split("\\.")[0];
                } else {
                    prefix = column.getPrefixTable();
                }

                String finalPrefix = prefix;
                StreamSupport
                        // 从 stmt.tables 获得 from clause 中的所有table
                        .stream(stmt.tables.spliterator(), false)
                        // 根据 alias 查询对应的 select 子查询
                        .filter(t -> t.getAliasClause().toString().equalsIgnoreCase(finalPrefix))
                        .findFirst().ifPresent(table -> {
                            table.subquery.getResultColumnList().forEach(tableColumn -> {
                                // 在子查询中搜索相同的column name
                                if (tableColumn.getDisplayName().equalsIgnoreCase(ColumnName)) {
                                    lineage.addFirst(String.format("%s(result of %s)",
                                            tableColumn.getDisplayName(),
                                            finalPrefix
                                    ));
                                    lineage.addFirst(String.format("%s(%s)",
                                            tableColumn.getDisplayName(),
                                            tableColumn.getPrefixTable()
                                    ));
                                }
                            });
                        });
            }
            for (LinkedList<String> lineage : lineages) {
                System.out.println(String.join(" -> ", lineage));
            }
        } else {
            System.out.println(sqlparser.getErrormessage());
        }
    }
}
